package com.study.userserviceprovider.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController

//@DefaultProperties
public class HystrixController{

    @Autowired
    private RestTemplate restTemplate;


    @HystrixCommand(commandProperties={
        @HystrixProperty(name="circuitBreaker.enabled",value="true"),
        @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="5"),
        @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="5000"),
        @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="50")
    },defaultFallback="fallback")
    @GetMapping("/getAllOrder/{num}")
    public String getAllOrder(@PathVariable("num") int num){
        if(num%2 == 0){
            return "正常访问";
        }
        return  restTemplate.getForObject("http://spring-cloud-order-service/orders",String.class);
    }


    private String fallback(){
        return  "系统繁忙";
    }

    @HystrixCommand(commandProperties={
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
    },defaultFallback="timeOutFallback")
    @GetMapping("/timeOutFallback")
    public String customJson(){
        return restTemplate.getForObject("http://8083/orders",String.class);
    }


    private String timeOutFallback(){
        return  "请求超时";
    }

}
